import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        socket = new Socket(serverIP,serverPort);
    }

    public void start() throws IOException {
        System.out.println("Clint start");

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {

            while (true) {
                //1. 读取用户输入
                Scanner scanner = new Scanner(System.in);
                System.out.print("——> ");
                String request = scanner.next();
                if (request.equals("exit")) break;

                //2. 将数据流发向服务器
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(request);
                writer.flush();

                //3. 响应服务器数据流
                Scanner scannerNetwork = new Scanner(inputStream);
                if (!scannerNetwork.hasNext()) break;
                String response = scannerNetwork.next();
                System.out.println("Server response: "+ response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",6666);
        client.start();
    }
}
